package de.matusystems


import org.apache.commons.io.IOUtils;
import org.codehaus.groovy.grails.commons.ApplicationHolder;

import com.amazonaws.AmazonClientException
import com.amazonaws.AmazonServiceException
import com.amazonaws.auth.PropertiesCredentials
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.GetObjectRequest
import com.amazonaws.services.s3.model.ObjectMetadata
import com.amazonaws.services.s3.model.PutObjectRequest
import com.amazonaws.services.s3.model.S3Object




class S3Service {


	private AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(ApplicationHolder.application.parentContext.getResource( File.separator + "WEB-INF" + File.separator + "AwsCredentials.properties").file))
	final String bucketName = "de.matusystems.services.buckets.images"

	def getFile(String key) {

		try {
			S3Object object = s3.getObject(new GetObjectRequest(bucketName, key))

			def fileMap = [:]
			fileMap['contentType'] = object.getObjectMetadata().getContentType()
			fileMap['file'] = IOUtils.toByteArray(object.getObjectContent())

			return fileMap
		} catch (AmazonServiceException ase) {
			printError(ase);
		} catch (AmazonClientException ace) {
			println "Error Message: " + ace.getMessage()
		}
	}

	def deleteFile(String key) {

		try {
			s3.deleteObject(bucketName, key);
		} catch (AmazonServiceException ase) {
			printError(ase);
		} catch (AmazonClientException ace) {
			println "Error Message: " + ace.getMessage()
		}
	}


	String storeFile(String filename, String contentType, byte[] file) {

		String key = new URLEncoder().encode(filename+"-"+new Date().time, "UTF-8")

		try {

			if(!s3.doesBucketExist(bucketName)){
				s3.createBucket(bucketName);
			}

			ObjectMetadata fileMetadata = new ObjectMetadata()
			fileMetadata.setContentType(contentType)
			s3.putObject(new PutObjectRequest(bucketName, key, new ByteArrayInputStream(file), fileMetadata))
			return key
		} catch (AmazonServiceException ase) {
			printError(ase)
		} catch (AmazonClientException ace) {
			println "Error Message: " + ace.getMessage()
		}
	}


	private void printError(AmazonServiceException ase) {
		println "Error Message:    " + ase.getMessage()
		println "HTTP Status Code: " + ase.getStatusCode()
		println "AWS Error Code:   " + ase.getErrorCode()
		println "Error Type:       " + ase.getErrorType()
		println "Request ID:       " + ase.getRequestId()
	}
}
